window.onload = function() {
    init();
};

function processspeech(query) {
    alert(query);
}

function speech() {
    //find which speech recognition constructor works
    if (typeof speechRecognition !== 'undefined') {
        return new speechRecognition();
    } else if (typeof mozSpeechRecognition !== 'undefined') {
        return new mozSpeechRecognition();
    } else if (typeof msSpeechRecognition !== 'undefined') {
        return new msSpeechRecognition();
    } else if (typeof webkitSpeechRecognition !== 'undefined') {
        return new webkitSpeechRecognition();
    }
    throw new Error('No speech recognition API detected.');
}

function init() {
    var recognition = speech();
    console.log(recognition);
    //listen once
    recognition.continuous = false;
    recognition.interimResults = true;
    //i'm english
    recognition.lang = 'pt-BR';
    //start listening
    recognition.start();

    //on each result
    recognition.addEventListener('result', function (event) {
        console.log(event);
        for (var i = event.resultIndex, len = event.results.length; i < len; i++) {
            //lastCommand.innerHTML = 'Último pedido: ' + event.results[i][0].transcript;
            lastCommand.innerHTML = 'Último pedido: ' + event.results[i][0].transcript;
            document.getElementById('testForm:hdnBtn').click();
            alert('teste');
        }
    }, false);

    recognition.addEventListener('start', function () {
        feedback.innerHTML = 'Estou pronto! Qual seu desejo, mestre?';
        button.style.display = 'none';
    }, false);

    recognition.addEventListener('speechstart', function () {
        feedback.innerHTML = 'Estou ouvindo...';
    }, false);

    recognition.addEventListener('speechend', function (event) {
        feedback.innerHTML = 'Não estou mais escutando...';
        init();
    }, false);
};
